package com.ghsc.ghxc.jsb.ui.integral.fragment

import android.os.Bundle
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.load
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.setOnFastClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.transformRoundCorner
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.RefreshListBinding
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.activity.IntegralOrderDetailActivity
import com.ghsc.ghxc.jsb.ui.integral.bean.IntegralOrderListDataBean
import com.ghsc.ghxc.jsb.ui.my.activity.OrderDetailActivity
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.fragment
 * 类名：MyBuyListFragment
 * 创建时间：2024/5/20 14:16
 * 创建人 @author： xiaolin
 * 描述 ：Todo...我买到的
 */
class MyBuyListFragment  : BaseVMFragment<IntegralSupermarketViewModel, RefreshListBinding>(R.layout.refresh_list) {
    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
       return  IntegralSupermarketViewModel::class.java
    }
    var index: Int = 0

    companion object {
        fun getInstance(index: Int): MyBuyListFragment? {
            var fragment = MyBuyListFragment()
            fragment.index = index
            return fragment
        }
    }
    override fun lazyLoad() {

    }

    var isInit=false
    private val mAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<IntegralOrderListDataBean>()
    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setEmptyView(R.layout.layout_order_empty)
        mAdapter.addChildClickViewIds(R.id.stvTuiKuan,R.id.stvSub)
        initRefreshLayout()
        pageNo = 1
        getListData()
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustKey.ORDER_TAB && rxBusBean.sign == CustKey.ORDER_TAB) {
                    var tabIndex =rxBusBean.anyBean as Int
                    if(tabIndex==index){
                        if (isInit){
                            binding.refreshLayout.autoRefresh()
                        }
                    }
                }
            }
    }

    override fun initClickListener() {
        super.initClickListener()
        mAdapter.setOnFastClickListener { data, position ->
            val bean = mAdapter.data[position]
            startKtxActivity<IntegralOrderDetailActivity>(
                values = arrayListOf(
                    "oid" to bean.oid,
                    "type" to 1,
                )
            )
        }

        mAdapter.setOnFastChildClickListener { view, position ->
            val bean = mAdapter.data[position]
            when (view.id) {
                R.id.stvTuiKuan -> {
                    //退款
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(requireActivity(),"提示","确定要退款吗?",
                                btnConfirm={
                                    val map: HashMap<String, Any> = HashMap()
                                    map["oid"] = bean.oid
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShopRefundMethod(it1) }
                                },
                                btnCancel={
                                },)
                        )
                        .show()
                }
                R.id.stvSub ->{
                    //确认收货
                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            ConfirmCancelPopViiew(requireActivity(),"提示","请您检查商品无误后再点击确认收货?",
                                btnConfirm={
                                    val map: HashMap<String, Any> = HashMap()
                                    map["oid"] = bean.oid
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShopConfirmMethod(it1) }
                                },
                                btnCancel={
                                },)
                        )
                        .show()
                }
            }
        }
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["otype"] = index
        loge("请求接口="+index+"当前页"+pageNo)
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShopOrderListMethod(it1) }
    }
    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MyBuyListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@MyBuyListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onShopOrderListData.observe(this@MyBuyListFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData(it.data.list)
                        mAdapter.setEmptyView(R.layout.layout_order_empty)
                    }
                    else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
                isInit=true
            }
            onShopRefundData.observe(this@MyBuyListFragment){
                showToast("操作成功")
                binding.refreshLayout.autoRefresh()
            }
            onShopConfirmData.observe(this@MyBuyListFragment){
                showToast("操作成功")
                binding.refreshLayout.autoRefresh()
            }

        }
    }
    inner class ListAdapter : BaseQuickAdapter<IntegralOrderListDataBean, BaseViewHolder>(R.layout.interstitial_order_item) {
        override fun convert(holder: BaseViewHolder, item: IntegralOrderListDataBean) {
            val ivOrderImg = holder.getView<ImageView>(R.id.ivOrderImg)
            ivOrderImg.load(item.skuimages, builder = {
                transform(transformRoundCorner(10))
            })
            holder.setText(R.id.tvOrderNumberHint,"订单编号:${item.oid}")
                .setText(R.id.tvOrderState,item.status)
                .setText(R.id.tvOrderName,item.title)
                .setText(R.id.tvPrice,item.price.toString())
                .setText(R.id.tvOrderCount,item.cnt.toString())
                .setText(R.id.tvOrderCategory,item.skuname)
                .setText(R.id.tvTotalPriceDesc,"共 ${item.cnt} 件商品:  ")
                .setText(R.id.tvPayRmb,item.total_price.toString())


            if(index==1){
                holder.setText(R.id.stvTuiKuan,"退 款" )
                    .setGone(R.id.stvTuiKuan,false)
            }else{
                holder.setGone(R.id.stvTuiKuan,true)
            }
            if(index==3){
                holder.setText(R.id.stvSub,"确认收货" )
                    .setGone(R.id.stvSub,false)
            }else{
                holder.setGone(R.id.stvSub,true)
            }
            if(index==5|| index==4){
                holder.setGone(R.id.llBtn,true)
            }else{
                holder.setGone(R.id.llBtn,false)
            }
        }
    }
}